package com.fhp;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.fhp.Bean.ExcelCarData;
import com.fhp.DAO.DataDao;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author liuxin
 */
@Slf4j
public class DataListener<E> implements ReadListener<ExcelCarData> {
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存数据
     */
    private List<ExcelCarData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final DataDao dataDao;
    public DataListener(DataDao dataDao){
        this.dataDao = dataDao;
    }

    /**
     * 每条数据解析时调用
     */
    @Override
    public void invoke(ExcelCarData data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT){
            saveData();
            // 存储完成清理List
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库!",cachedDataList.size());
        dataDao.save(cachedDataList);
        log.info("存储数据库成功!");
    }

    /**
     * 所有数据解析完成后调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 保存数据，防止遗漏
        saveData();
        log.info("所有数据解析完成!");
    }
}
